<?php
namespace Hawk\Controller;
use Think\Controller;
class CommonController extends Controller {
	/**
     * echarts 柱状图数据计算
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
	public function shuju(){
		$model=M('');
		//分组业绩涉及人员(默认当月业绩)
		$where['role_name']='销售主任';
		$where['operate_time']=array('gt',date('Y-m',time()));
		$list = $this->_yeji($where);
		//部门
		$part = $this->_part(array('role_name'=>array('eq','销售主任')));
		foreach ($part as $k => $v){
			$data['part_name'][$k]=substr($v['name'], 6);
			foreach ($list as $key => $value) {
				if($v['id']==$value['part_id']){
					$data['yeji'][$k]=intval($value['yeji']);
				}else{
					if($data['yeji'][$k]==0){
						$data['yeji'][$k]=0;
					}					
				}
			}			
		}
		echo json_encode($data);	
	}
	/**
     * echarts 饼图业绩计算
     * @author hawk <2271030162@qq.com>
     * @param  $role_name string
     * @return array
     */
	public function alldata(){
		//分部业绩
		$data['manager_data']=$this->_alldata('销售经理');
		foreach ($data['manager_data'] as $k => $v) {
			$part1[]=$v['name'];
		}
		//分组业绩
		$data['head_data'] = $this->_alldata('销售主任');
		foreach ($data['head_data'] as $k => $v) {
			$part2[]=$v['name'];
		}
		//部门
		$data['part'] = array_merge($part1,$part2);
		echo json_encode($data);
	}
	/**
     * 角色分级算业绩
     * @author hawk <2271030162@qq.com>
     * @param  $role_name string
     * @return array
     */
	private function _alldata($role_name,$part){
		$where['role_name']=$role_name;
		$where['operate_time']=array('gt',date('Y-m',time()));
		$list = $this->_yeji($where);
		foreach ($list as $k => $v) {
			$data[$k]['value'] = intval($v['yeji']);
			$data[$k]['name']=substr($v['name'], 6);			
		}
		return $data;
	}
	/**
     * 业绩
     * @author hawk <2271030162@qq.com>
     * @param  $where array
     * @return array
     */
	private function _yeji($where=array()){
		$model = M('');
		$admin =$model
		->table(C('DB_PREFIX').'admin')
		->field('a.part_id,p.name,ar.role_id,sum(md.OpFare*md.percent) as yeji')
		->alias('a')
		->group('a.part_id')
		->join('left join hawk_part p on a.part_id=p.id left join hawk_admin_role ar on a.id=ar.admin_id left join hawk_role r on ar.role_id=r.id left join hawk_money_divide md on a.id=md.sale_worker')
		->where($where)
		->order('sort asc')
		->select();
		return $admin;
	}
	/**
     * 部门
     * @author hawk <2271030162@qq.com>
     * @param  $where array
     * @return array
     */
	private function _part($where=array()){
		$model =M('');
		$part = $model
		->table(C('DB_PREFIX').'part')
		->field('p.*')
		->alias('p')
		->group('p.id')
		->join('left join hawk_admin a on a.part_id=p.id left join hawk_admin_role ar on a.id=ar.admin_id left join hawk_role r on r.id=ar.role_id')
		->order('sort asc')
		->where($where)
		->select();
		return $part;
	}
}